package avicit.bdp.dms.das.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dms.das.dao.ColumnTypeDao;
import avicit.bdp.dms.das.dto.ColumnReservedDTO;
import avicit.bdp.dms.das.dto.ColumnTypeDTO;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @修改记录：
 */
@Service
public class ColumnTypeService extends BaseService<ColumnTypeDao, ColumnTypeDTO> {

	private final ColumnReservedService columnReservedService;

    public ColumnTypeService(ColumnReservedService columnReservedService) {
        this.columnReservedService = columnReservedService;
    }

    /**
	 * 获取字段类型和限制
	 *
	 * @param type
	 * @return
	 */
	public List<ColumnTypeDTO> getColumnTypeListByType(String type) {
		ColumnTypeDTO query = new ColumnTypeDTO();
		query.setType(type);
		return this.selectList(query)
				.stream()
				.sorted(Comparator.comparing(ColumnTypeDTO::getName, Comparator.nullsLast(Comparator.naturalOrder())))
				.collect(Collectors.toList());
	}

	public Map<String, Object> getTableInfoByType(String type) {
		Map<String, Object> result = new HashMap<>(16);
		List<ColumnTypeDTO> list = this.selectListByType(type);
		result.put("coumnFieldList", list);
		ColumnReservedDTO queryReserved = new ColumnReservedDTO();
		queryReserved.setType(type);
		List<ColumnReservedDTO> reservedDTOList = columnReservedService.selectList(queryReserved);
		if (!reservedDTOList.isEmpty()) {
			ColumnReservedDTO reservedDTO = reservedDTOList.get(0);
			Map<String, Object> reservedMap = JSONUtils.toMap(reservedDTO.getName(), String.class, Object.class);
			result.putAll(reservedMap);
		}
		return result;
	}

	private List<ColumnTypeDTO> selectListByType(String type) {
		return this.mapper.selectListByType(type);
	}
}
